#Copyright Ken Faulkner 2007.
import cPickle
from Common.logRoutine import *
import traceback
import os
import os.path

class Cache( object ):
  """
  Cache routines.
  Just serialise data to a disk, the filename being the date of the data.

  Need to figure out a way to remove old entries from the cache dir!

  """
  def __init__(self, config ):
    self.config = config
    self.log = getLogger()
    self.home_dir = os.path.join( os.getenv("HOME"), ".bbc" )
    self.cache_dir = os.path.join( self.home_dir, "cache" )


  def set( self, key, val ):
    """
    Set the value based off the key, duh 
    """

    self.log.info("Cache::set start")

    try:
      data = cPickle.dumps( val )

      filename = os.path.join(self.cache_dir, str( key ) )

      fd = open( filename, 'w')
      fd.write( data )
      fd.close()

    except:
      self.log.info("Cache::set ex " + traceback.format_exc() )
    


  def get( self, key ):
    """
    Get the value based off the key, duh 
    """

    self.log.info("Cache::get start")

    val = None

    try:

      filename = os.path.join(self.cache_dir, str( key ) )

      self.log.debug("trying to load " + filename )
      
      fd = open( filename, 'r')
      data = fd.read()
      fd.close()

      val = cPickle.loads( data )

    except:
      self.log.info("Cache::get ex " + traceback.format_exc() )
    
    return val

